//
//  WBBaseVC.m
//  WeatherBar
//
//  Created by yby on 2024/6/7.
//

#import "WBBaseVC.h"
#import "UIImage+WBImage.h"
#import "UIBarButtonItem+WBCreate.h"
#import "UINavigationBar+WBNavBar.h"

@interface JYNavigationTitleView : UIView

@property (nonatomic, strong) UILabel *var_titleLabel;

@property (nonatomic, strong) UILabel *var_subtitleLabel;

@end


@implementation JYNavigationTitleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _var_titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _var_titleLabel.font = kBoldFontSize(16);
        _var_titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
        _var_titleLabel.textAlignment = NSTextAlignmentCenter;
        
        _var_subtitleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _var_subtitleLabel.textColor = [UIColor grayColor];
        _var_subtitleLabel.font = kFontSize(12);
        _var_subtitleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
        _var_subtitleLabel.textAlignment = NSTextAlignmentCenter;
        
        [self addSubview:_var_titleLabel];
        [self addSubview:_var_subtitleLabel];
    }
    return self;
}

- (CGSize)sizeThatFits:(CGSize)size
{
    CGFloat var_margin = 80.f;
    CGFloat var_maxWidth = [UIScreen mainScreen].bounds.size.width - var_margin * 2;
    
    [self.var_titleLabel sizeToFit];
    self.var_titleLabel.wb_width = MIN(self.var_titleLabel.wb_width, var_maxWidth);
    
    [self.var_subtitleLabel sizeToFit];
    self.var_subtitleLabel.wb_width = MIN(self.var_subtitleLabel.wb_width, var_maxWidth);
    
    CGFloat var_width = MAX(self.var_titleLabel.wb_width, self.var_subtitleLabel.wb_width);
    return CGSizeMake(var_width, self.var_titleLabel.wb_height + self.var_subtitleLabel.wb_height);
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.var_titleLabel.wb_centerX = self.wb_width * .5f;
    self.var_subtitleLabel.wb_centerX = self.wb_width * .5f;
    self.var_subtitleLabel.wb_bottom  = self.wb_height;
}

@end


@interface WBBaseVC () <UINavigationControllerDelegate>
{
    NSString *_var_navTitle;
    NSString *_var_startTimeStr;
    NSString *_var_endTimeStr;
}
@property (nonatomic ,strong) UILabel *var_navTitleLabel;
/// 自定义导航类型
@property (nonatomic ,assign) WBNavBarType var_navType;

@property (nonatomic ,copy) NSString *var_date;

@end

@implementation WBBaseVC

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDarkContent;
}
+ (UIViewController *)wb_instanceSelfWithParam:(NSDictionary *)param
{
    UIViewController *vc = [[self alloc] init];
    [vc setValuesForKeysWithDictionary:param];
    return vc;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _var_leftGestureEnable = YES;
    
    [self.navigationController.navigationBar wb_setBackgroundColor:[UIColor colorFFF]];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if (@available(iOS 11.0, *)) {
        
    } else {
        self.edgesForExtendedLayout = UIRectEdgeNone;// 推荐使用
    }
    
    if (kIsBangsScreen) {
        if (@available(iOS 11.0, *)) {
            self.additionalSafeAreaInsets = UIEdgeInsetsMake(0, 0, kSafeAreaBottomHeight, 0);
        } else {
            // Fallback on earlier versions
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    /// 设置吗系统导航背景色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage wb_imageWithColor:[UIColor colorFFF]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage wb_imageWithColor:[UIColor colorFFF]]];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationController.delegate=self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
    NSLog(@" %@挂了",self.class);
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController*)navigationController willShowViewController:(UIViewController*)viewController animated:(BOOL)animated
{
    if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        return;
    }
    if([viewController isKindOfClass:[WBBaseVC class]]){
        [navigationController setNavigationBarHidden:((WBBaseVC *) viewController).var_hiddenNavigationBar animated:YES];
    }else
    {
        [navigationController setNavigationBarHidden:YES animated:YES];
    }
}

#pragma mark - 自定义Nav方法
/** 隐藏系统的nav，显示自定义的Nav */
- (void)wb_showCustomerNavBarWithType:(WBNavBarType)type
{
    self.var_navType = type;
    
    _var_navBar = [[WBNavBar alloc] initWithType:self.var_navType];
    @weakify(self);
    [self.var_navBar.var_didClickBackSubject subscribeNext:^(id x) {
        @strongify(self);
//        [self.navigationController popViewControllerAnimated:YES];
        [self wb_navBackButtonClicked:nil];
    }];
    [self.var_navBar.var_didClickSearchSubject subscribeNext:^(id x) {
        @strongify(self);
        [self wb_searchButtonClick];
    }];
    [self.var_navBar.var_didClickRithtSubject subscribeNext:^(id x) {
        @strongify(self);
        [self wb_customerNavRightButtonClick];
    }];
    
    self.var_hiddenNavigationBar = YES;
    [self.view addSubview:self.var_navBar];
}
/**
 *    @brief    自定义titlte居中处理
 */
- (void)wb_setNavTitle:(NSString *)title
{
    JYNavigationTitleView *var_titleView = (JYNavigationTitleView *)self.navigationItem.titleView;
    if (!var_titleView || ![var_titleView isKindOfClass:[JYNavigationTitleView class]])
    {
        var_titleView = [[JYNavigationTitleView alloc] initWithFrame:CGRectZero];
        self.navigationItem.titleView = var_titleView;
        
        var_titleView.var_titleLabel.text = title;
    }
    
    [var_titleView sizeToFit];
    
    _var_navTitle = title;
    _var_navTitleLabel = var_titleView.var_titleLabel;
}

/**
 *    @brief    更新自定义titlte居中处理
 *
 *    @param     text     title
 */
- (void)wb_updateNavTitle:(NSString *)title
{
    JYNavigationTitleView *var_titleView = (JYNavigationTitleView *)self.navigationItem.titleView;
    if (!var_titleView || ![var_titleView isKindOfClass:[JYNavigationTitleView class]])
    {
        [self wb_setNavTitle:title];
    } else {
        _var_navTitleLabel.text = title;
        _var_navTitle = title;
    }
}

- (void)wb_setNavRightButtonwithImg:(NSString *)normalImg selImg:(NSString *)selImg title:(NSString *)title action:(SEL)action
{
    self.navigationItem.rightBarButtonItem = [self wb_getButtonItemWithImg:normalImg selImg:selImg title:title action:action left:NO];
}

- (void)wb_setNavLeftButtonwithImg:(NSString *)normalImg selImg:(NSString *)selImg title:(NSString *)title action:(SEL)action
{
    self.navigationItem.leftBarButtonItem = [self wb_getButtonItemWithImg:normalImg selImg:selImg title:title action:action left:YES];
}

- (void)wb_setNavCancelText {
    [self wb_setNavLeftButtonwithImg:nil selImg:nil title:@"取消" action:@selector(wb_navBackButtonClicked:)];
}

- (void)wb_setNavBackArrow {
    /// 适配iOS11按钮偏移问题
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 11.0) {
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem wb_itemWithTarget:self action:@selector(wb_navBackButtonClicked:) image:[UIImage imageNamed:@"icon_navBack"] imageEdgeInsets:UIEdgeInsetsMake(0, -6, 0, 0)];
    }else{
        UIButton *var_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        var_backButton.exclusiveTouch = YES;
        [var_backButton setImage:[UIImage imageNamed:@"icon_navBack"] forState:UIControlStateNormal];
        var_backButton.frame = CGRectMake(0, 0, 40, 40);
        [var_backButton addTarget:self action:@selector(wb_navBackButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        //配置返回按钮距离屏幕边缘的距离
        UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
        spaceItem.width =  -15;
        var_backButton.imageEdgeInsets =UIEdgeInsetsMake(0, -5,0, 0);
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:var_backButton];
        self.navigationItem.leftBarButtonItems = @[spaceItem,backItem];
    }
}

- (void)wb_setNavNextArrow {
}
- (void)wb_setSearchButton
{
    UIButton *var_searchButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 54.f, 32.f)];
    [var_searchButton setTitleColor:[UIColor color999] forState:UIControlStateNormal];
    [var_searchButton setImage:[UIImage imageNamed:@"top_search.png"] forState:UIControlStateNormal];
//    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    var_searchButton.titleLabel.font = kFontSize(16);
    [var_searchButton addTarget:self action:@selector(wb_searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* var_rightItem = [[UIBarButtonItem alloc] initWithCustomView:var_searchButton];
    self.navigationItem.rightBarButtonItem = var_rightItem;
}
- (void)wb_setNavRightButtonEnable:(BOOL)enable
{
    [self.navigationItem.rightBarButtonItem setEnabled:enable];
}

- (void)wb_setNavLeftButtonEnable:(BOOL)enable
{
    [self.navigationItem.leftBarButtonItem setEnabled:enable];
}

- (void)wb_setNavTransluent:(BOOL)transluent
{
    if (transluent) {
        
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"CommonTransparentImg"] forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTranslucent:YES];
        //    为什么要加这个呢，shadowImage 是在ios6.0以后才可用的。但是发现5.0也可以用。不过如果你不判断有没有这个方法，
        //    而直接去调用可能会crash，所以判断下。作用：如果你设置了上面那句话，你会发现是透明了。但是会有一个阴影在，下面的方法就是去阴影
        if ([self.navigationController.navigationBar respondsToSelector:@selector(shadowImage)])
        {
            [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
        }
        
        self.extendedLayoutIncludesOpaqueBars = YES;
        //将会
        if (kIsBangsScreen) {
            self.navigationController.navigationBar.wb_height = [UIDevice wb_fullNavHeight]-20;
            
            self.edgesForExtendedLayout = UIRectEdgeTop;
        }else{
            
            self.edgesForExtendedLayout = UIRectEdgeTop;
        }
    }
}

- (void)wb_restoreNavNoTransluent
{
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
/// 隐藏系统navBar
- (void)setVar_hiddenNavigationBar:(BOOL)hiddenNavigationBar
{
    _var_hiddenNavigationBar = hiddenNavigationBar;
}
- (void)wb_setCustomerNavAlpha:(CGFloat)alpha
{
    [self.var_navBar wb_setupAlpha:alpha];
}
- (void)wb_setCustomerNavSearchBarPlaceHolder:(NSString *)placeHolder;
{
    self.var_navBar.var_placeHolder = placeHolder;
}
#pragma mark - NavButton点击
- (void)wb_navBackToHomeButtonClicked:(UIButton *)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)wb_navBackButtonClicked:(UIButton *)sender
{
//    [self.view wb_dismissLoading];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)wb_searchButtonClick{
    
}
- (void)wb_customerNavRightButtonClick{
    
}

#pragma mark - MG_NavBaseViewController private
- (UIBarButtonItem *)wb_getButtonItemWithImg:(NSString *)norImg selImg:(NSString *)selImg title:(NSString *)title action:(SEL)action left:(BOOL)left
{
    CGSize var_navbarSize = self.navigationController.navigationBar.bounds.size;
    CGRect var_frame = CGRectMake(0, 0, var_navbarSize.height, var_navbarSize.height);
    
    UIButton *var_button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [var_button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    var_button.exclusiveTouch = YES;
    if (norImg)
        [var_button setImage:[UIImage imageNamed:norImg] forState:UIControlStateNormal];
    if (selImg)
        [var_button setImage:[UIImage imageNamed:selImg] forState:UIControlStateHighlighted];
    if (title) {
        CGSize var_strSize = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]}];
        [var_button setTitle:title forState:UIControlStateNormal];
        [var_button.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [var_button setTitleColor:[UIColor color777] forState:UIControlStateNormal];
        //        [button setTitleColor:RGBA(198, 198, 198, 1) forState:UIControlStateHighlighted];
        var_frame.size.width = MAX(var_frame.size.width, var_strSize.width + 20);
        
        if (left) {
            var_button.titleEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15);
        }
        else {
            var_button.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, -15);
        }
    }
    else {
        if (left) {
            var_button.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 15);
        }
        else {
            var_button.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, -15);
        }
    }
    
    var_button.frame = var_frame;
    UIBarButtonItem* var_tmpBarBtnItem=[[UIBarButtonItem alloc] initWithCustomView:var_button];
    return var_tmpBarBtnItem;
}

- (UIImageView *)wb_findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *var_subview in view.subviews) {
        UIImageView *var_imageView = [self wb_findHairlineImageViewUnder:var_subview];
        if (var_imageView) {
            return var_imageView;
        }
    }
    return nil;
}

/// 添加已成处理界面
+ (UIView *)wb_addExceptionHandlingView:(UIView *)view frame:(CGRect)frame {
    UIView *var_backView = [[UIView alloc]initWithFrame:frame];
    var_backView.backgroundColor = [UIColor whiteColor];
    var_backView.hidden = YES;
    [view addSubview:var_backView];
    return var_backView;
}

#pragma mark - 加载指示器
/// 开始加载显示
- (void)wb_beginLoading
{
    [self.view wb_beginLoading];
}
/// 隐藏加载显示
- (void)wb_endLoading
{
    [self.view wb_endLoading];
}

#pragma mark - 配置回调
/// 重试按钮回调
/// @param block 回调
- (void)wb_configRetryAction:(void (^)(void))block
{
    [self.view wb_configReloadAction:block];
}
/// 返回按钮回调
/// @param block 回调
- (void)wb_configBackAction:(void (^)(void))block
{
    [self.view wb_configBackAction:block];
}

#pragma mark - 空视图（EmptyControlView）推荐

/// 图片类型、文字、按钮类型
/// @param frame 空视图Frame
/// @param imageType 图片类型（无数据、无网络）
/// @param titleName 可自定义描述文字
/// @param buttonType 按钮类型（隐藏、刷新、返回、Push）
- (void)wb_showEmptyControlViewWitnFrame:(CGRect)frame
                            imageType:(HTEmptyImageType)imageType
                            titleName:(NSString *)titleName
                           buttonType:(HTEmptyButtonType)buttonType
                           buttonName:(NSString *)buttonName
{
    [self.view wb_showEmptyControlViewWitnFrame:frame
                               fullScreen:CGRectEqualToRect(frame, CGRectZero)? YES : NO imageType:(HTEmptyImageType)imageType
                                   titleName:titleName
                                  buttonType:buttonType
                                  buttonName:buttonName];
}

/// 图片名、文字、按钮类型
/// @param frame 空视图Frame
/// @param imageName 可自定义图片展示
/// @param titleName 可自定义描述文字
/// @param buttonType 按钮类型（隐藏、刷新、返回、Push）
- (void)wb_showEmptyControlViewWitnFrame:(CGRect)frame
                            imageName:(NSString *)imageName
                            titleName:(NSString *)titleName
                           buttonType:(HTEmptyButtonType)buttonType
                           buttonName:(NSString *)buttonName
{
    [self.view wb_showEmptyControlViewWitnFrame:frame
                               fullScreen:CGRectEqualToRect(frame, CGRectZero)? YES : NO
                                   imageName:imageName
                                   titleName:titleName
                                  buttonType:buttonType
                                  buttonName:buttonName];
}

/// 隐藏空数据页面
- (void)wb_hiddenEmptyControlView {
    [self.view wb_hiddenEmptyControlView];
}



@end
